﻿#include "netserver.h"

NetServer::NetServer(QObject *parent) : QObject(parent)
{
    _ctcpServer = new CTcpServer;
    _thread = new QThread;
    _ctcpServer->moveToThread(_thread);
    this->moveToThread(_thread);
    _thread->start();
    connect(this,SIGNAL(sigStart(quint16)),this,SLOT(slotStart(quint16)),Qt::QueuedConnection);
    connect(this,SIGNAL(sigStop()),this,SLOT(slotStop())/*,Qt::QueuedConnection*/);
    connect(this,SIGNAL(sigWrite(QString,int,char*,int)),this,SLOT(slotWrite(QString,int,char*,int)),Qt::BlockingQueuedConnection);
    connect(_ctcpServer,SIGNAL(sig_receiveData(QByteArray,QString,quint16)),this,SLOT(SlotreceiveData(QByteArray,QString,quint16))/*,Qt::BlockingQueuedConnection*/);
    connect(_ctcpServer,SIGNAL(sig_readyRead(QString,quint16)),this,SLOT(slot_readyRead(QString,quint16))/*,Qt::BlockingQueuedConnection*/);
    connect(_ctcpServer,SIGNAL(sig_clientConnected(QString,int)),this,SLOT(slot_clientConnected(QString,int))/*,Qt::BlockingQueuedConnection*/);


}

NetServer::~NetServer()
{
    _thread->quit();
    _thread->wait();

    delete _ctcpServer;
    delete _thread;

}

void NetServer::Start(quint16 servPort)
{
    emit sigStart(servPort);
}

void NetServer::Stop()
{
    emit sigStop();
}

void NetServer::Read(QString ip,quint16 port,char *data, int len)
{
    emit sigRead(ip,port,data,len);
}

void NetServer::Write(const QString &ip,
                      int port,char *data, int len)
{
    emit sigWrite(ip,port,data,len);
}

void NetServer::slotStart(quint16 servPort)
{
	_ctcpServer->slot_start(servPort);
}

void NetServer::slotStop()
{
    _ctcpServer->slot_stop();
}

void NetServer::slotRead(QString ip,quint16 port,char *data, int len)
{
    _ctcpServer->slot_ReadData(ip,port,data,len);
}

void NetServer::slotWrite(const QString &ip,
                          int port,char *data, int len)
{
    _ctcpServer->slot_writeData(ip,port,data,len);
}

void NetServer::SlotreceiveData(QByteArray data,QString ip,quint16 port)
{
    emit sig_receiveData(data,ip,port);
//    qDebug() << data.toHex();
}

void NetServer::slot_readyRead(QString ip, quint16 port)
{
    emit sig_readyRead(ip,port);
}

void NetServer::slot_clientConnected(QString ip, int port)
{
    qDebug() <<"new Client " << ip << port;
//    emit sig_clientConnected(ip,port);
}
